package com.ruoyi.web.controller.system;

import java.math.BigDecimal;
import java.sql.Time;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.system.domain.Member;
import com.ruoyi.system.domain.Records;
import com.ruoyi.system.mapper.MemberMapper;
import com.ruoyi.system.service.IMemberService;
import com.ruoyi.system.service.IRecordsService;
import com.ruoyi.system.service.impl.SysConfigServiceImpl;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 会员管理Controller
 *
 * @author ruoyi
 * @date 2021-09-24
 */
@Controller
@RequestMapping("/system/member")
public class MemberController extends BaseController
{
    private String prefix = "system/member";

    @Autowired
    private IMemberService memberService;
    @Autowired
    private IRecordsService recordsService;
    @Autowired
    private SysConfigServiceImpl sysConfigService;

    @RequiresPermissions("system:member:view")
    @GetMapping()
    public String member()
    {
        return prefix + "/member";
    }

    /**
     * 查询会员管理列表
     */
    @RequiresPermissions("system:member:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Member member)
    {
        startPage();
        List<Member> list = memberService.selectMemberList(member);
        return getDataTable(list);
    }

    /**
     * 导出会员管理列表
     */
    @RequiresPermissions("system:member:export")
    @Log(title = "会员管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Member member)
    {
        List<Member> list = memberService.selectMemberList(member);
        ExcelUtil<Member> util = new ExcelUtil<Member>(Member.class);
        // 获取当前的用户信息
        SysUser currentUser = ShiroUtils.getSysUser();
        Records records = new Records();
        records.setUserName(currentUser.getUserName());
        records.setMsg("导出会员列表");
        records.setTime(new Date());
        records.setVipName("导出");
        recordsService.insertRecords(records);
        return util.exportExcel(list, "会员管理数据");
    }

    /**
     * 新增会员管理
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存会员管理
     */
    @RequiresPermissions("system:member:add")
    @Log(title = "会员管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Member member)
    {
        // 获取当前的用户信息
        SysUser currentUser = ShiroUtils.getSysUser();
        Records records = new Records();
        records.setUserName(currentUser.getUserName());
        records.setVipName(member.getNameVip());
        records.setCreateBy(currentUser.getUserName());
        records.setCreateTime(new Date());
        records.setMsg("新增会员"+member.getNameVip());
        records.setTime(new Date());
        recordsService.insertRecords(records);
        member.setCreateTime(new Date());
        member.setCreatePeople(currentUser.getUserName());


        return toAjax(memberService.insertMember(member));
    }

    /**
     * 修改会员管理
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {

        Member member = memberService.selectMemberById(id);

        mmap.put("member", member);
        return prefix + "/edit";
    }

    /**
     * 修改保存会员管理
     */
    @RequiresPermissions("system:member:edit")
    @Log(title = "会员管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Member member)
    {
        // 获取当前的用户信息
        SysUser currentUser = ShiroUtils.getSysUser();
        Records records = new Records();
        records.setUserName(currentUser.getUserName());
        records.setVipName(member.getNameVip());
        records.setCreateBy(currentUser.getUserName());
        records.setCreateTime(new Date());
        records.setMsg("修改会员信息-"+member.getNameVip());
        records.setVipId(member.getId()+"");
        records.setTime(new Date());
        recordsService.insertRecords(records);
        return toAjax(memberService.updateMember(member));
    }

    /**
     * 删除会员管理
     */
    @RequiresPermissions("system:member:remove")
    @Log(title = "会员管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        String[] array = Convert.toStrArray(ids);
        String names = "";
        String idarr = "";
        for(int i =0 ;i<array.length;i++){
            Long id = Long.parseLong(array[i]);
            Member member = memberService.selectMemberById(id);
            names = names+"<" + member.getNameVip()+">";
            idarr = idarr +"<" + member.getId()+">";
        }

        // 获取当前的用户信息
        SysUser currentUser = ShiroUtils.getSysUser();
        Records records = new Records();
        records.setUserName(currentUser.getUserName());
        records.setVipName(names);
        records.setCreateBy(currentUser.getUserName());
        records.setCreateTime(new Date());
        records.setMsg("删除会员信息-"+names);
        records.setVipId(idarr);
        records.setTime(new Date());
        recordsService.insertRecords(records);
        return toAjax(memberService.deleteMemberByIds(ids));
    }

    /**
     * 会员消费
     */
    @RequiresPermissions("system:member:pay")
    @Log(title = "会员消费", businessType = BusinessType.UPDATE)
    @PostMapping( "/pay")
    @ResponseBody
    public AjaxResult pay(Long id)
    {
        // 获取当前的用户信息
        SysUser currentUser = ShiroUtils.getSysUser();
        Member member = memberService.selectMemberById(id);
        Records records = new Records();
        String price1 = sysConfigService.selectConfigByKey("product_price");
        if(price1 == null || "".equals(price1)){
            return AjaxResult.error("未找到商品价格，请在系统参数里设置商品价格");
        }
        BigDecimal price = null;
        try{
            price = new BigDecimal(price1);
        }catch (Exception e){
            return AjaxResult.error("请在系统参数里设置正确商品价格");
        }
        records.setUserName(currentUser.getUserName());
        records.setVipName(member.getNameVip());
        records.setCreateBy(currentUser.getUserName());
        records.setCreateTime(new Date());
        records.setVipId(member.getId()+"");
        records.setTime(new Date());
        if("0".equals(member.getCardStatus())){
            if(member.getTimesNow() > 0){
                member.setTimesNow(member.getTimesNow() -1);
                memberService.updateMember(member);
                records.setMsg(member.getNameVip()+"消费次卡一次");
            }else{
                return AjaxResult.error("会员卡剩余次数不足");
            }
        }else if("1".equals(member.getCardStatus())){
            if(member.getMoneyNow().compareTo(price) >= 0){
                member.setMoneyNow(member.getMoneyNow().subtract(price));
                memberService.updateMember(member);
                records.setMsg(member.getNameVip()+"消费一次，消费金额："+price1);
            }else{
                return AjaxResult.error("会员卡余额不足");
            }
        }
        else{
            records.setMsg(member.getNameVip()+"-会员卡消费，会员卡类型："+member.getCardStatus());
        }
        recordsService.insertRecords(records);
        return AjaxResult.success();
    }
}
